#include "server_poll_tcp.h"

int main(int argc, char *argv[])
{
    int fd_listen = tcp_server_init("0", 8888, 20);
    ERROR_CHECK(fd_listen, -1, "tcp_server_init");
    struct pollfd fd_s[128];
     memset(fd_s, 0, sizeof(fd_s));
    for (size_t i = 0; i < 128; i++)
    {
        fd_s[i].fd = -1;
    }
    int index = 0,fd;
    fd_s[index].fd = fd_listen;
    fd_s[index].events = POLLIN;
    index++;
    while (1)
    {
        int ret = poll(fd_s, index, -1);
        ERROR_CHECK(-1, ret, "poll");
        for (int i = 0; i < index; i++)
        {
             
            if (fd_s[i].revents == POLLIN)
            {
                  fd = fd_s[i].fd;
                if (fd== fd_listen)
                {
                      
                    int fd_cnd = tcp_server_wait(fd);
                    if (-1 == fd_cnd)
                    {
                        perror("wait");
                        continue;
                    }
                    fd_s[index].fd = fd_cnd;
                    fd_s[index].events = POLLIN;
                    index++;
                    
                }
                else
                { 
                    if (-1 == sendfile(fd))
                    {
                        close(fd);
                        for (size_t j = i; j < index - 1; j++)
                        {
                            fd_s[j] = fd_s[j + 1];
                            index--;
                        }
                    }
                }
            }
          
            // else if (fd_s[i].revents == POLLOUT)
            // {

            // }
        }
    }

    return 0;
}
